package com.hwj.netty;


import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Configuration
@ChannelHandler.Sharable
@Slf4j
public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public Map<String, Channel> cmap = new HashMap<>();


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("与客户端建立连接，通道开启！");
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("与客户端断开连接，通道关闭！");
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        //接收的消息
        Map map = JSON.parseObject(msg.text(), Map.class);
        String type = map.get("type").toString();
        switch (type){
            case "1":   // 登录
                websocketLogin(map,ctx);
                break;
            case "2": // 发送对话消息
                send(map);
                break;
        }
        log.info(String.format("收到客户端%s的数据：%s", ctx.channel().id(), msg.text()));
    }
    private void send(Map map) {
        String receiverId = map.get("receiverId").toString();
        if (cmap.containsKey("user"+receiverId)){
            Channel channel = cmap.get("user" + receiverId);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",2); // 对话
            obj.put("uuid", UUID.randomUUID().toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            log.info("未登录");
        }
    }
    private void websocketLogin(Map map,ChannelHandlerContext ctx) {
        String loginUserId = map.get("loginUserId").toString();
        cmap.put("user"+loginUserId,ctx.channel());
        log.info(loginUserId+"登录");
    }
}